import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import axios from 'axios'

export default class Search extends Component {
    Search = async() => {
        // 获取用户的输入 (连续解构赋值+重命名)
       let { keyWordeNode: { value: keyWord } } = this;
        // 发送请求前通知List更新状态
        PubSub.publish('listPubSub', {isFirst:false, isLoading:true})

        //#region 
        /*  axios.get(`http://localhost:3000/search/users?q=${keyWord}`).then(
            res => {
                // console.log('成功了', res.data);
                // 发送请求后通知List更新状态
                PubSub.publish('listPubSub', {isLoading:false, users:res.data.items})
            },
            err => {
                // console.log('失败了', err);
                // 发送请求失败后通List更新状态
                PubSub.publish('listPubSub', {isLoading:false, err:err.message})
            }
        ) */
        //#endregion

        //#region 
        /* fetch(`http://localhost:3000/search/users?q=${keyWord}`).then(
            req => {
                return req.json()
            }
        ).then(
            data => {
                console.log('成功' + data.items);
                PubSub.publish('listPubSub', {isLoading:false, users:data.items})
            }
        ).catch(
            err => {
               console.log('失败了'+err); 
               PubSub.publish('listPubSub', {isLoading:false, err:err.message})
            }
        ) */
        //#endregion

        try {
            let reqPromise = await (await fetch(`http://localhost:3000/search/users?q=${keyWord}`));
            let data = await reqPromise.json();
            PubSub.publish('listPubSub', {isLoading:false, users:data.items})
        } catch (err) {
            console.log('失败了'+err); 
            PubSub.publish('listPubSub', {isLoading:false, err:err.message})  
        }
        
    }

    render() {
        return (
            <section className="jumbotron">
                <h3 className="jumbotron-heading">搜索github用户</h3>
                <div>
                    <input ref={c => this.keyWordeNode = c} type="text" placeholder="输入关键词点击搜索" />&nbsp;
                    <button onClick={this.Search}>搜索</button>
                </div>
            </section>
        )
    }
}
